Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

282
Vistas
"Uncaught TypeError: Cannot read properties of undefined (reading FetchApi.js:23 'data')" when refresh the page

When the code runs for the first time, it's mappings data as I wanted. But when I refresh the page it shows an error. Does anyone know how can I fix this error and what causes it?

The code

import React, { useEffect, useState } from 'react';
import axios from 'axios';

const FetchApi = () => {

const [items, setItems] = useState();

useEffect(() => {
    getUser();
}, [])

async function getUser() {
    try {
        const response = await axios.get('https://datausa.io/api/data?drilldowns=Nation&measures=Population');
        setItems(response.data.data)
        return items;
    } catch (error) {
        console.error(error);
    }
}

return (
    <div>
        {
            items.map(item => (
                <li key={item.Year}>
                    {item.Nation}
                </li>
            ))
        }
    </div>
  )
}

export default FetchApi

Output when runs for the first time enter image description here

Error when refresh the page

enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I found the problem.

The problem was, "items" is undefined in its default state. It should be

const [items, setItems] = useState([]);

And I think the reason this error shows only when refresh the page was,

when I change the code and save, it changes the html view automatically but the browser only reads the changed JavaScript codes so the const [items, setItems] = useState(); line never reads at first.

But when I refresh the page the code runs from the beginning and it catches that "items" is undefined and shows the error.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda